/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 23735
 * Date: 2023-08-04
 * Time: 10:58
 */

import java.util.concurrent.atomic.AtomicInteger;

class MyThread extends Thread {
    private int num;
    // 注意这里不能使用 Integer, 虽然 Integer 是引用类型, 但是不可变, 其他的包装类也是
    // 每次对 Integer 进行修改的话, 都会创建一个新的变量
    private AtomicInteger count;

    public MyThread(int num, AtomicInteger count) {
        this.num = num;
        this.count = count;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            count.incrementAndGet();
            System.out.println("Thread: " + num + ": " + count);
        }
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger count = new AtomicInteger(0);
        Thread t1 = new MyThread(1, count);
        Thread t2 = new MyThread(2, count);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(count);
    }
}

class Counter {
    private int value = 0;

    public synchronized void increment() {
        value++;
    }

    public synchronized int getValue() {
        return value;
    }
}

class MyThread2 extends Thread {
    private int num;
    private Counter counter;

    public MyThread2(int num, Counter counter) {
        this.num = num;
        this.counter = counter;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            synchronized (counter) {
                counter.increment();
                System.out.println("Thread: " + num + ": " + counter.getValue());
            }
        }
    }
}

class Main2 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        Thread t1 = new MyThread2(1, counter);
        Thread t2 = new MyThread2(2, counter);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(counter.getValue());
    }
}
